/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
package example.springboot.service;

import example.springboot.dto.PageRequest;
import example.springboot.dto.PageResult;
import example.springboot.dto.WordDTO;
import example.springboot.dto.ImportResult;
import example.springboot.entity.Word;
import example.springboot.mapper.WordMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WordService {

    @Autowired
    private WordMapper wordMapper;

    /**
     * 根据ID查询单词
     */
    public Word findById(Integer id) {
        return wordMapper.findById(id);
    }

    /**
     * 分页查询单词列表
     */
    public PageResult<WordDTO> getWordList(PageRequest pageRequest) {
        Integer offset = (pageRequest.getPage() - 1) * pageRequest.getSize();
        List<Word> words = wordMapper.findByPage(offset, pageRequest.getSize(), pageRequest.getSearch());
        Long total = wordMapper.countWords(pageRequest.getSearch());

        // 转换为DTO
        List<WordDTO> wordDTOs = words.stream().map(word -> {
            WordDTO dto = new WordDTO();
            BeanUtils.copyProperties(word, dto);
            return dto;
        }).collect(Collectors.toList());

        return new PageResult<>(wordDTOs, total);
    }

    /**
     * 创建单词
     */
    public Word createWord(Word word) {
        // 检查单词是否已存在
        Word existWord = wordMapper.findByWord(word.getWord());
        if (existWord != null) {
            throw new RuntimeException("单词\"" + word.getWord() + "\"已存在");
        }
        
        // 设置默认值
        if (word.getFlag() == null) {
            word.setFlag(0);
        }
        
        wordMapper.insert(word);
        return word;
    }

    /**
     * 更新单词
     */
    public boolean updateWord(Word word) {
        Word existWord = wordMapper.findById(word.getId());
        if (existWord == null) {
            throw new RuntimeException("单词不存在");
        }

        return wordMapper.update(word) > 0;
    }

    /**
     * 删除单词
     */
    public boolean deleteWord(Integer id) {
        return wordMapper.deleteById(id) > 0;
    }

    /**
     * 批量导入单词
     * Excel格式：第一列-单词，第二列-音标，第三列-释义，第四列-英文例句，第五列-中文例句
     */
    public ImportResult importWords(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            ImportResult result = new ImportResult();

            // 从第2行开始读取（跳过表头）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }

                try {
                    // 读取单词（必填）
                    Cell wordCell = row.getCell(0);
                    if (wordCell == null || getCellValue(wordCell).trim().isEmpty()) {
                        result.getErrors().add("第" + (i + 1) + "行：单词不能为空");
                        continue;
                    }
                    String word = getCellValue(wordCell).trim();

                    // 检查单词是否已存在
                    Word existWord = wordMapper.findByWord(word);
                    if (existWord != null) {
                        result.setSkipCount(result.getSkipCount() + 1);
                        result.getSkippedWords().add(word);
                        continue;
                    }

                    // 读取其他字段
                    String phonetic = getCellValue(row.getCell(1));
                    String meaning = getCellValue(row.getCell(2));
                    String exampleEn = getCellValue(row.getCell(3));
                    String exampleCn = getCellValue(row.getCell(4));

                    // 创建单词对象
                    Word newWord = new Word();
                    newWord.setWord(word);
                    newWord.setPhonetic(phonetic);
                    newWord.setMeaning(meaning);
                    newWord.setExampleSentenceEn(exampleEn);
                    newWord.setExampleSentenceCn(exampleCn);
                    newWord.setFlag(0);

                    // 插入数据库
                    wordMapper.insert(newWord);
                    result.setSuccessCount(result.getSuccessCount() + 1);

                } catch (Exception e) {
                    result.getErrors().add("第" + (i + 1) + "行：" + e.getMessage());
                }
            }

            workbook.close();
            inputStream.close();

            // 设置错误数量
            result.setErrorCount(result.getErrors().size());

            // 如果所有数据都有错误且没有成功导入，抛出异常
            if (result.getSuccessCount() == 0 && result.getSkipCount() == 0 && result.getErrorCount() > 0) {
                throw new RuntimeException("导入失败：所有数据都有错误。错误详情：" + String.join("; ", result.getErrors()));
            }

            return result;

        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("导入失败：" + e.getMessage());
        }
    }

    /**
     * 获取单元格值
     */
    private String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf((long) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}

